/*
 * @author yjiewei
 * @date 2022/3/19 23:12
 */
package com.wu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
//import com.wu.cmn.client.DictFeignClient;
import com.wu.yygh.cmn.client.DictFeignClient;
import com.wu.yygh.common.result.Result;
import com.wu.yygh.hosp.repository.HospitalRepository;
import com.wu.yygh.hosp.service.HospitalService;
import com.wu.yygh.model.hosp.Hospital;
import com.wu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Resource
    private HospitalRepository hospitalRepository;

    @Resource
    private DictFeignClient dictFeignClient;


    /**
     * 将请求的数据保存到MongoDB中
     * @param map
     */
    @Override
    public void save(Map<String, Object> map) {

        // 首先将json数据转换成字符串，再转换成hospital对象
        // 本质上map就是一个json数据
        // 这俩操作很重要
        String hospitalString = JSONObject.toJSONString(map);
        Hospital hospital = JSONObject.parseObject(hospitalString, Hospital.class);

        // 判断是否存在数据
        String hoscode = hospital.getHoscode();
        Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);

        // 不存在则添加
        if (Objects.isNull(hospitalExist)) {
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }else {
            // 否则修改
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }

    }

    /**
     * 查询医院数据
     */
    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    /**
     * 分页查询医院信息
     */
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo queryVo) {

        // 页面参数
        // 没有page-1报错 Page 2 of 1 containing UNKNOWN instances
        Pageable pageable = PageRequest.of(page-1, limit);

        // 创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(queryVo, hospital);

        // 创建example对象 我理解的这个对象其实就是个条件值+一个匹配规则
        Example<Hospital> example = Example.of(hospital, matcher);

        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);

        /**
         *  处理医院等级信息
         *  获取到医院列表，但是我们这里是没有对应的参数去赋值的，
         *  但是有一个param可以添加其他参数，它是hashMap结构
         */
        List<Hospital> hospitals = hospitalPage.getContent();

        hospitals.forEach(this::setHospitalByHostype);

        return hospitalPage;
    }

    /**
     * 更新医院状态 上线还是未上线
     */
    @Override
    public void updateStatus(String id, Integer status) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);

    }

    @Override
    public Map<String, Object> getHospitalById(String id) {
        Map<String, Object> map = new HashMap<>();
        Hospital hospital = hospitalRepository.findById(id).get();
        // 单独处理预定规则
        map.put("bookingRule", hospital.getBookingRule());
        // 不用重复返回
        hospital.setBookingRule(null);
        map.put("hospital", hospital);
        return map;
    }

    // 获取医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if(hospital != null) {
            return hospital.getHosname();
        }
        return null;
    }

    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> item(String hoscode) {

        HashMap<String, Object> result = new HashMap<>();
        Hospital hospital = this.getByHoscode(hoscode);
        // 医院详情
        this.setHospitalByHostype(hospital);
        // 预约规则
        result.put("bookingRule", hospital.getBookingRule());
        // 不需要重复返回
        hospital.setBookingRule(null);
        result.put("hospital", hospital);
        return result;
    }

//    /**
//     * 设置医院等级信息
//     */
//    private void setHospitalByHostype(Hospital hos) {
//        // 根据dictCode和value获取医院等级名称
//        String name = dictFeignClient.getName("Hostype", hos.getHostype());
//        hos.getParam().put("hosTypeString", name);
//
//        // 查询省市地区
//        String province = dictFeignClient.getName(hos.getProvinceCode());
//        String city = dictFeignClient.getName(hos.getCityCode());
//        String district = dictFeignClient.getName(hos.getDistrictCode());
//        hos.getParam().put("fullAddress", province + city + district);
//
//    }


    @Override
    public Map<String, Object> getHospById(String id) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = hospitalRepository.findById(id).get();
        this.setHospitalByHostype(hospital);
        //医院基本信息（包含医院等级）
        result.put("hospital",hospital);
        //单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    /**
     * 设置医院等级信息
     */
    private void setHospitalByHostype(Hospital hos) {
        // 根据dictCode和value获取医院等级名称
        Result name = dictFeignClient.getName("Hostype", hos.getHostype());
        hos.getParam().put("hosTypeString", name.getData());

        // 查询省市地区
        Result province = dictFeignClient.getName(hos.getProvinceCode());
        Result city = dictFeignClient.getName(hos.getCityCode());
        Result district = dictFeignClient.getName(hos.getDistrictCode());
        hos.getParam().put("fullAddress", province.getData().toString() + city.getData() + district.getData());

    }
}
